﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace VCommons
{
    public class CookieAction
    {
        static string MAINSITEDOMAINNAME = WebConfig.GetWebConfig("Domain", "eee114.com");
        static string DEBUGDOMAINNAME = "localhost";
        /// <summary>
        /// 网站主域名
        /// </summary>
        public static string CookiesDomain
        {
            get
            {
                if (System.Web.HttpContext.Current.Request.Url.Host.EndsWith(DEBUGDOMAINNAME, StringComparison.CurrentCultureIgnoreCase))
                {
                    return DEBUGDOMAINNAME;
                }
                else if (System.Web.HttpContext.Current.Request.Url.Host.EndsWith(MAINSITEDOMAINNAME, StringComparison.CurrentCultureIgnoreCase))
                {
                    return MAINSITEDOMAINNAME;
                }
                else
                {
                    return null;
                }
            }
        }
        #region 写入Cookie
        /// <summary>
        /// 写入读取Cookie
        /// </summary>
        /// <param name="name">Cookie名称</param>
        /// <param name="value">Cookie值</param>
        public static void WriteCookie(string name, string value)
        {
            WriteCookie(name, value, 191844000);
        }

        /// <summary>
        /// 写入读取Cookie
        /// </summary>
        /// <param name="name">Cookie名称</param>
        /// <param name="value">Cookie值</param>
        /// <param name="expiresMinutes">Cookie的过期时间（单位：分钟）</param>
        public static void WriteCookie(string name, string value, int expiresMinutes)
        {
            HttpContext context = HttpContext.Current;
            HttpCookie cookies = new HttpCookie(name, value);
            cookies.Domain = CookiesDomain; // ".eee114.com";
            cookies.Expires = DateTime.Now.AddMinutes(expiresMinutes);
            context.Response.Cookies.Add(cookies);
        }


        #endregion

        #region 读取Cookie
        /// <summary>
        /// 读取读取Cookie
        /// </summary>
        /// <param name="name">读取Cookie名称</param>
        /// <returns>读取Cookie值</returns>
        public static string ReadCookie(string name)
        {

            if (null != System.Web.HttpContext.Current.Request.Cookies && null != System.Web.HttpContext.Current.Request.Cookies[name])
            {
                return System.Web.HttpContext.Current.Request.Cookies[name].Value.ToString();
            }
            else
            {
                return "";
            }
        }
        #endregion
    }
}
